package com.ccrfid.rmc6.lbservice3.client;

import com.ccrfid.rmc6.appconfig.websocket.MsgEntity;
import com.ccrfid.rmc6.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

public class WsClient extends WebClient {
    private static final Logger logger = LoggerFactory.getLogger(WsClient.class);
    private WebSocketSession session;

    public WsClient(String clientId, String userAccount, List<String> clientIpAddrs, WebSocketSession session) {
        super(clientId, userAccount, clientIpAddrs);
        this.session = session;
    }

    public WebSocketSession getSession() {
        return session;
    }

    public void setSession(WebSocketSession session) {
        this.session = session;
    }

    @Override
    public void postMsg(String msgType, String msgContent) throws IOException {
        MsgEntity<String> msg = new MsgEntity<>(msgType, msgContent);
        synchronized (session) {
            session.sendMessage(new TextMessage(JsonUtil.INSTANCE.writeValueAsString(msg)));
        }
        logger.debug("WebSocket -- post to client: {}/{}, msgType: {}, msgContent: {}",
                getClientId(), getClientIpAddrs(), msgType, msgContent);
    }

    @Override
    public void postMsg(MsgEntity<?> msgEntity) throws IOException {
        String txt = JsonUtil.INSTANCE.writeValueAsString(msgEntity);
        synchronized (session) {
            session.sendMessage(new TextMessage(txt));
        }
        logger.debug("WebSocket -- post to client: {}/{}, msgEntity: {}", getClientId(), getClientIpAddrs(), txt);
    }

    @Override
    public void closeConnection() {
        synchronized (session) {
            if (session.isOpen()) {
                try {
                    session.close();
                    logger.debug("WebSocket -- close connection, clientId: {}", getClientId());
                } catch (IOException ex) {
                    ex.printStackTrace();
                    logger.error("WebSocket -- close connection error, clientId: {}", getClientId());
                }
            }
        }
    }
}
